<?php


/*
 * Data Access Object for Match
 */
class MatchDao {

    var $select = "select m.match_id, m.gate, m.home_record, m.away_record, m.match_type, date_format(m.date_played, '%b %e %Y'), m.teams_updated from matches m";

    function findTeamMatches($teamId) {
        $matches = array ();
        $rs = executeQuery($this->select .
        ", match_records h, match_records a " .
        "where m.match_id=a.match_id " .
        "and m.away_record=a.match_record_id " .
        "and m.match_id=h.match_id " .
        "and m.home_record=h.match_record_id " .
        "and (a.team_id=$teamId or h.team_id=$teamId) " .
        "order by date_played desc, match_id desc");
        $mrd = new MatchRecordDao();
        while ($row = mysql_fetch_row($rs)) {
            $match = $this->initMatch($row, $mrd);
            array_push($matches, $match);
        }

        return $matches;
    }

    function findSeasonMatches(& $season) {
        global $teams;
        $matches = new Matches();
        $rs = executeQuery($this->select . " where fk_season_id=$season->id order by date_played asc, match_id asc");
        $mrd = new MatchRecordDao();
        while ($row = mysql_fetch_row($rs)) {
            $match = $this->initMatch($row, $mrd);
            $teams->addMatchResult($match);
            array_push($matches->matches, $match);
        }

        $matches->matches = array_reverse($matches->matches);
        return $matches;
    }

    function findMatch($matchId) {
        $rs = executeQuery($this->select . " where match_id=$matchId");
        $mrd = new MatchRecordDao();
        if ($row = mysql_fetch_row($rs)) {
        	return $this->initMatch($row, $mrd);
        }
    }

    function initMatch($row, & $mrd) {
        $homeRec = $mrd->load($row[2]);
        $awayRec = $mrd->load($row[3]);
        $match = new Match();
        $match->init($row[0], $row[1], $homeRec, $awayRec, $row[4], $row[5], $row[6]);
        return $match;
    }

    function finalCheck(& $match) {
        if ($match->isFinal()) {
            if (isset ($match->season)) {
                $match->season->finalMatch($match);
            }
        }
    }

    function create(& $match) {
        global $season;
        $seasonId = $match->season->id;
        $home = $match->homeRec->id;
        $away = $match->awayRec->id;
        $rs = executeQuery("insert into matches (match_id, fk_season_id, home_record, away_record, gate, match_type, date_played, teams_updated) values ($match->id, $seasonId, $home, $away, $match->gate, '$match->type', '$match->datePlayed', 0)");
        if ($rs) {
            $mrd = new MatchRecordDao();
            $mrd->create($match, $match->homeRec);
            $mrd->create($match, $match->awayRec);
        }

        $ad = new ApprovalDao();
        if ($match->season->opponentApproval) {
            $this->createApproval($ad, $match->id, $match->homeRec->teamId, $ad->home);
            $this->createApproval($ad, $match->id, $match->awayRec->teamId, $ad->away);
        }
        if ($match->season->commissionerApproval) {
            $this->createCoachApproval($ad, $match->id, $season->commissionerId, $ad->commissioner);
        }
        $this->finalCheck($match);
    }

    function createApproval($dao, $matchId, $teamId, $type) {
        global $teams;
        $team = $teams->getTeam($teamId);
        $this->createCoachApproval($dao, $matchId, $team->coach->id, $type, $team->coach);
    }

    function createCoachApproval($dao, $matchId, $coachId, $type, $coach = null) {
        $approval = new Approval();
        $approval->matchId = $matchId;
        $approval->expectedCoachId = $coachId;
        $approval->approvalType = $type;
        $dao->create($approval, $coach);
    }

    function update($match, $updateApprovals = true) {
        executeQuery("update matches set gate=$match->gate, match_type='$match->type', teams_updated=$match->teamsUpdated where match_id=$match->id");
        $this->finalCheck($match);

        if ($updateApprovals) {
            global $loggedin;
            $ad = new ApprovalDao();
            $approvals = $ad->findMatchApprovals($match);
            foreach ($approvals as $approval) {
                if (!$approval->isCommissioner() and $loggedin->id == $approval->expectedCoachId) {
                    $approval->approve();
                } else {
                    $approval->unapprove();
                }
                $ad->save($approval);
            }
        }
    }

    function delete($match) {
        if (!isCommissioner()) {
            return false;
        }

        $homeId = $match->homeRec->id;
        $awayId = $match->awayRec->id;

        // match purchases
        executeQuery("delete from match_record_player_purchases where fk_match_record_id in ($homeId, $awayId)");

        // player deltas 
        executeQuery("delete from player_deltas where fk_match_record_id in ($homeId, $awayId)");

        // match records
        executeQuery("delete from match_records where match_id=$match->id");

        // match
        executeQuery("delete from matches where match_id=$match->id");

        $ad = new ApprovalDao();
        $ad->deleteApprovals($match->id);

        return true;

    }

    function checkMatch($homeTeamId, $awayTeamId, $gate) {
        global $teams, $loggedin;
        // check data for errors
        if ($homeTeamId == $awayTeamId) {
            logger("You cannot play yourself, $homeTeamId vs $awayTeamId");
            return false;
        }

        if (!isset ($gate) or $gate < 4000) {
            logger("You must enter a value for the gate, $gate");
            return false;
        }

        $homeTeam = $teams->getTeam($homeTeamId);
        $awayTeam = $teams->getTeam($awayTeamId);
        if (!$this->canEditMatch($homeTeam, $awayTeam)) {
            logger("You can only submit your own results, " . $loggedin->id . ", " . $homeTeam->coach->id . " vs " . $awayTeam->coach->id);
            return false;
        }

        return true;
    }

    function canEditMatch($homeTeam, $awayTeam) {
        global $loggedin;
        if ($loggedin->isAdmin())
            return true;
        global $teams;
        if ($homeTeam->coach->id == $loggedin->id || $awayTeam->coach->id == $loggedin->id) {
            return true;
        }
        return false;
    }

    function addMatch($homeTeamId, $awayTeamId, $homeTD, $awayTD, $homeCas, $awayCas, $gate, $matchType, $year, $month, $day) {
        global $teams, $matches, $season;
        $rc = $this->checkMatch($homeTeamId, $awayTeamId, $gate);
        if (!$rc) {
            return 0;
        }

        $rs = executeQuery("select max(match_id) from matches");
        $row = mysql_fetch_row($rs);
        $match = new Match();
        $match->id = 1 + $row[0];
        $match->season = $season;
        $match->gate = $gate;
        $match->type = $matchType;
        $match->datePlayed = "" . $year . "-" . $month . "-" . $day;

        $match->homeRec = new MatchRecord();
        $match->awayRec = new MatchRecord();
        $match->awayRec->id = (2 * $match->id);
        $match->homeRec->id = (2 * $match->id) - 1;

        $match->homeRec->score = $homeTD;
        $match->homeRec->casualties = $homeCas;
        $match->homeRec->teamId = $homeTeamId;
        $homeTeam = $teams->getTeam($homeTeamId);
        $match->homeRec->tv = $homeTeam->getTR();

        $match->awayRec->score = $awayTD;
        $match->awayRec->casualties = $awayCas;
        $match->awayRec->teamId = $awayTeamId;
        $awayTeam = $teams->getTeam($awayTeamId);
        $match->awayRec->tv = $awayTeam->getTR();

        $this->create($match);
        $teams->addMatchResult($match);
        array_push($matches->matches, $match);

        // clear up fixtures
        executeQuery("delete FROM fixtures WHERE (fk_away_team=$awayTeamId and fk_home_team=$homeTeamId) OR (fk_away_team=$homeTeamId and fk_home_team=$awayTeamId) order by round, id limit 1");

        return $match->id;
    }
}
?>
